import React, { useState, useRef, useEffect } from 'react';
import styles from './MainColor.module.css';

const MainColor = () => {
    const [colors, setColors] = useState([]);
    const [imageUrl, setImageUrl] = useState('');
    const [selectedPosition, setSelectedPosition] = useState(null);
    const [draggingIndex, setDraggingIndex] = useState(null);
    const [scale, setScale] = useState(1);
    const [position, setPosition] = useState({ x: 0, y: 0 });
    const canvasRef = useRef(null);
    const imgRef = useRef(null);
    const canvasContainerRef = useRef(null);
    const isDraggingCanvas = useRef(false);
    const lastPosition = useRef({ x: 0, y: 0 });

    const handleImageUpload = (e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = () => {
                setImageUrl(reader.result);
            };
            reader.readAsDataURL(file);
        }
    };

    const getPixelColor = (ctx, x, y) => {
        const pixel = ctx.getImageData(x, y, 1, 1).data;
        return {
            r: pixel[0],
            g: pixel[1],
            b: pixel[2],
            hex: rgbToHex(pixel[0], pixel[1], pixel[2])
        };
    };

    const rgbToHex = (r, g, b) => {
        return '#' + [r, g, b].map(x => {
            const hex = x.toString(16);
            return hex.length === 1 ? '0' + hex : hex;
        }).join('');
    };

    const extractInitialColors = (img) => {
        const canvas = canvasRef.current;
        const ctx = canvas.getContext('2d');
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);

        const positions = {
            top: { x: Math.floor(img.width / 2), y: 0 },
            right: { x: img.width - 1, y: Math.floor(img.height / 2) },
            bottom: { x: Math.floor(img.width / 2), y: img.height - 1 },
            left: { x: 0, y: Math.floor(img.height / 2) },
            center: { x: Math.floor(img.width / 2), y: Math.floor(img.height / 2) }
        };

        const initialColors = Object.entries(positions).map(([position, coords]) => ({
            position,
            ...getPixelColor(ctx, coords.x, coords.y),
            x: coords.x,
            y: coords.y
        }));

        setColors(initialColors);
    };

    // 添加缩放处理函数
    const handleWheel = (e) => {
        e.preventDefault();
        const delta = e.deltaY;
        const newScale = delta > 0 
            ? Math.max(0.5, scale - 0.1)
            : Math.min(3, scale + 0.1);
        setScale(newScale);
    };

    // 添加画布拖动相关函数
    const handleCanvasMouseDown = (e) => {
        if (e.button === 1) { // 中键
            e.preventDefault();
            isDraggingCanvas.current = true;
            lastPosition.current = { x: e.clientX, y: e.clientY };
        }
    };

    const handleCanvasMouseMove = (e) => {
        if (isDraggingCanvas.current) {
            const deltaX = e.clientX - lastPosition.current.x;
            const deltaY = e.clientY - lastPosition.current.y;
            lastPosition.current = { x: e.clientX, y: e.clientY };
            
            setPosition(prev => ({
                x: prev.x + deltaX,
                y: prev.y + deltaY
            }));
        }
    };

    const handleCanvasMouseUp = () => {
        isDraggingCanvas.current = false;
    };

    // 修改获取坐标的函数以考虑缩放和位移
    const getScaledCoordinates = (clientX, clientY) => {
        const rect = canvasRef.current.getBoundingClientRect();
        const x = (clientX - rect.left - position.x) / scale;
        const y = (clientY - rect.top - position.y) / scale;
        return { x, y };
    };

    // 修改点击处理函数
    const handleCanvasClick = (e) => {
        if (!canvasRef.current || isDraggingCanvas.current) return;
        
        const { x, y } = getScaledCoordinates(e.clientX, e.clientY);
        const ctx = canvasRef.current.getContext('2d');
        const color = getPixelColor(ctx, x, y);
        
        setColors(prev => [...prev, {
            position: `自选位置 ${prev.length + 1}`,
            ...color,
            x,
            y
        }]);
    };

    // 修改标记点拖动处理函数
    const handleMouseMove = (e) => {
        if (draggingIndex === null) return;

        const { x, y } = getScaledCoordinates(e.clientX, e.clientY);
        updateColorPosition(draggingIndex, x, y);
    };

    const removeColor = (index) => {
        setColors(prev => prev.filter((_, i) => i !== index));
    };

    const updateColorPosition = (index, x, y) => {
        const canvas = canvasRef.current;
        const ctx = canvas.getContext('2d');
        const color = getPixelColor(ctx, x, y);

        setColors(prev => prev.map((item, i) => {
            if (i === index) {
                return {
                    ...item,
                    ...color,
                    x,
                    y
                };
            }
            return item;
        }));
    };

    const handleMarkerMouseDown = (index, e) => {
        e.stopPropagation();
        setDraggingIndex(index);
    };

    const handleMouseUp = () => {
        setDraggingIndex(null);
    };

    useEffect(() => {
        if (imageUrl) {
            const img = new Image();
            img.src = imageUrl;
            img.onload = () => extractInitialColors(img);
        }
    }, [imageUrl]);

    useEffect(() => {
        document.addEventListener('mouseup', handleMouseUp);
        document.addEventListener('mousemove', handleMouseMove);

        return () => {
            document.removeEventListener('mouseup', handleMouseUp);
            document.removeEventListener('mousemove', handleMouseMove);
        };
    }, [draggingIndex]);

    useEffect(() => {
        const container = canvasContainerRef.current;
        if (container) {
            container.addEventListener('wheel', handleWheel, { passive: false });
            container.addEventListener('mousedown', handleCanvasMouseDown);
            container.addEventListener('mousemove', handleCanvasMouseMove);
            container.addEventListener('mouseup', handleCanvasMouseUp);
            
            return () => {
                container.removeEventListener('wheel', handleWheel);
                container.removeEventListener('mousedown', handleCanvasMouseDown);
                container.removeEventListener('mousemove', handleCanvasMouseMove);
                container.removeEventListener('mouseup', handleCanvasMouseUp);
            };
        }
    }, [scale]);

    return (
        <div className={styles.container}>
            <input 
                type="file" 
                accept="image/*" 
                onChange={handleImageUpload}
                className={styles.fileInput}
            />
            
            {imageUrl && (
                <div className={styles.colorPickerContainer}>
                    <div 
                        className={styles.imageContainer}
                        ref={canvasContainerRef}
                    >
                        <div 
                            className={styles.canvasWrapper}
                            style={{
                                transform: `scale(${scale}) translate(${position.x}px, ${position.y}px)`,
                                transformOrigin: '0 0'
                            }}
                        >
                            <canvas 
                                ref={canvasRef}
                                onClick={handleCanvasClick}
                                className={styles.clickableCanvas}
                            />
                            {colors.map((color, index) => (
                                <div
                                    key={index}
                                    className={styles.colorMarker}
                                    style={{
                                        backgroundColor: color.hex,
                                        left: color.x,
                                        top: color.y,
                                        cursor: draggingIndex === index ? 'grabbing' : 'grab',
                                        transform: `translate(-50%, -50%) scale(${1/scale})`
                                    }}
                                    onMouseDown={(e) => handleMarkerMouseDown(index, e)}
                                >
                                    <div 
                                        className={styles.colorMarkerLabel}
                                        style={{ transform: `scale(${1/scale})` }}
                                    >
                                        {color.position}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                    
                    <div className={styles.colorPalette}>
                        {colors.map((color, index) => (
                            <div 
                                key={index}
                                className={styles.colorItem}
                            >
                                <div 
                                    className={styles.colorBox}
                                    style={{ backgroundColor: color.hex }}
                                />
                                <div className={styles.colorInfo}>
                                    <span>{color.position}</span>
                                    <span>{color.hex}</span>
                                </div>
                                <button 
                                    onClick={() => removeColor(index)}
                                    className={styles.removeButton}
                                >
                                    ×
                                </button>
                            </div>
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
};

export default MainColor;